<template>
  <el-container>
    <el-header>
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <h2>新建外贸销售订单</h2>
        <el-input
          v-model="temp.order_no"
          placeholder="自动生成订单编号"
          :disabled="auto_order_no"
          style="width: 400px; margin: 0 20px;"
        >
          <!-- ... -->
        </el-input>
        <div>
          <span style="color:#909090">处理人:</span>
          <span>{{ temp.manager }}</span>
        </div>
      </div>
    </el-header>
    <el-main style="padding: 0 20px 100px 20px;">
      <el-collapse v-model="activeName1" accordion style="margin-bottom: 20px; width: 100%">
        <el-collapse-item title="基本信息" name="1">
          <el-row class="form-row">
            <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
              <el-form ref="form1" :model="temp" :rules="rules" label-position="right" label-width="80px" style="width: 438px;display: inline-block; margin-bottom: 20px;">
                <el-form-item label="币种" prop="currency">
                  <el-select v-model="temp.currency" placeholder="请选择">
                    <el-option
                      v-for="item in currencys"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="订单名称" prop="name">
                  <el-input v-model="temp.name" placeholder="请输入订单名称" />
                </el-form-item>
                <el-form-item label="订单状态">
                  <el-select
                    v-model="temp.crmorderstate_id"
                    filterable
                    clearable
                    reserve-keyword
                    placeholder="选择订单状态"
                  >
                    <el-option
                      v-for="item in orderStates"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="贸易方式">
                  <el-input v-model="temp.trade_type" placeholder="贸易方式" />
                </el-form-item>
                <el-form-item label="发票号">
                  <el-input v-model="temp.invoice_number" placeholder="请输入发票号" />
                </el-form-item>
                <el-form-item label="交货日期">
                  <el-date-picker
                    v-model="temp.ending_date"
                    align="right"
                    type="date"
                    placeholder="选择日期"
                    :picker-options="pickerOptions"
                  />
                </el-form-item>
                <el-form-item label="客户需求">
                  <el-input v-model="temp.quote" type="textarea" />
                </el-form-item>
              </el-form></el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
              <el-form ref="form2" :model="temp" :rules="rules" label-position="right" label-width="80px" style="width: 438px;display: inline-block; margin-bottom: 20px;">
                <el-form-item label="客户名称" prop="crmcustomer__name">
                  <el-input v-model="temp.crmcustomer__name" placeholder="请输入订单名称" />
                </el-form-item>
                <el-form-item label="客户国家" prop="crmcustomer__country">
                  <el-select v-model="temp.crmcustomer__country" filterable clearable placeholder="请选择">
                    <el-option
                      v-for="item in countries"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="客户公司">
                  <el-input v-model="temp.crmcustomer__company" placeholder="客户公司名称" />
                </el-form-item>
                <el-form-item label="客户邮箱">
                  <el-input v-model="temp.crmcustomer__mail" placeholder="客户邮箱" />
                </el-form-item>
                <el-form-item label="客户电话">
                  <el-input v-model="temp.crmcustomer__phone" placeholder="客户电话号码" />
                </el-form-item>
                <el-form-item label="whatsapp">
                  <el-input v-model="temp.crmcustomer__whatsapp" placeholder="whatsapp" />
                </el-form-item>
                <el-form-item label="客户来源">
                  <el-select v-model="temp.crmcustomer__source" placeholder="请选择">
                    <el-option
                      v-for="item in customer_sources"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>
      <el-collapse v-model="activeName2" accordion style="margin-bottom: 30px; width: 100%">
        <el-collapse-item title="订单产品" name="2">
          <el-row>
            <el-link type="primary" style="float: right; margin-right: 20px; margin-bottom: 10px;" @click="producDrawerVisible=true">添加产品</el-link>
          </el-row>
          <el-row style="margin-bottom: 20px;">
            <el-table
              :data="temp.products"
              border
              fit
              highlight-current-row
              :default-sort="{prop: 'create_at', order: 'descending'}"
              style="width: 100%"
            >
              <el-table-column align="left" label="产品名称" width="200" prop="cnname" sortable="custom">
                <template slot-scope="scope">
                  <h3>{{ scope.row.enname }}</h3>
                  <span style="display: block">中文名称:{{ scope.row.cnname }}</span>
                  <span style="display: block">产品编码：{{ scope.row.sku }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" width="150" label="型号" prop="model" sortable="custom" />
              <el-table-column align="center" width="150" label="产品类型" prop="product_type" sortable="custom" />
              <el-table-column align="center" label="数量" prop="quantity" sortable="custom">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.quantity" :min="1" placeholder="数量" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="PI交货周期" prop="pi_lead_period" sortable="custom">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.pi_lead_period" :min="1" placeholder="数量" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="供货周期" prop="manufacture_lead_period" sortable="custom">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.manufacture_lead_period" :min="1" placeholder="数量" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="技术参数" prop="parameters" sortable="custom">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.parameters" type="textarea" :rows="3" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="备注信息" prop="note" sortable="custom">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.note" type="textarea" :rows="3" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" fixed="right" width="100">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-delete"
                    plain
                    @click="handleDeleteFromTable(scope.$index)"
                  >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </el-collapse-item>
      </el-collapse>
      <el-alert
        title="提示"
        type="warning"
        description="初始化信息，可以不填产品信息，后续加入即可"
        show-icon
        style="margin-bottom: 10px;"
      />
      <el-alert
        title="提示"
        type="warning"
        description="客户信息将会自动添加进入客户信息池"
        show-icon
        style="margin-bottom: 30px;"
      />
    </el-main>
    <el-footer style="position: fixed;width: 100%; height: 60px; z-index: 1000; left:0px;bottom:0px; background-color: #fff; box-shadow: 0 -2px 10px rgba(0,0,0,.1); display: flex; align-items: center; justify-content: flex-end; padding-right: 30px;">
      <el-button type="success" style="width:100px" :loading="createloading" @click="handleCreateOrder">保存</el-button>
    </el-footer>
    <el-drawer
      :wrapper-closable="false"
      title="新增产品"
      append-to-body
      size="50%"
      :visible.sync="producDrawerVisible"
      direction="rtl"
    >
      <div style="margin: 20px; padding-bottom: 60px;">
        <el-form ref="product" :model="product" :rules="product_rules" label-position="right" label-width="160px" style="width: 438px;display: inline-block;">
          <el-form-item label="产品名称" prop="cnname">
            <el-autocomplete
              v-model="product.cnname"
              placeholder="请输入产品中文名称或部分名称进行搜索"
              style="width: 100%"
              :fetch-suggestions="querySearchProduct"
              @select="handleProductSelect"
            />
          </el-form-item>

          <el-form-item label="英文名称" prop="enname">
            <el-input v-model="product.enname" placeholder="请输入产品英文名称" />
          </el-form-item>

          <el-form-item label="SKU编号" prop="sku">
            <el-input v-model="product.sku" placeholder="请输入SKU编号" />
          </el-form-item>

          <el-form-item label="产品类型" prop="product_type">
            <el-select v-model="product.product_type" placeholder="请选择">
              <el-option label="主产品" value="主产品" />
              <el-option label="配件" value="配件" />
            </el-select>
          </el-form-item>

          <el-form-item label="产品图片" prop="image">
            <el-input v-model="product.image" placeholder="请输入图片URL" />
          </el-form-item>

          <el-form-item label="数量" prop="quantity">
            <el-input-number v-model="product.quantity" :min="1" placeholder="数量" />
          </el-form-item>

          <el-form-item label="产品型号" prop="model">
            <el-input v-model="product.model" placeholder="请输入产品型号" />
          </el-form-item>

          <el-form-item label="技术参数" prop="parameters">
            <el-input v-model="product.parameters" type="textarea" placeholder="请输入技术参数等其他信息" />
          </el-form-item>

          <el-form-item label="PI交货周期(天)" prop="pi_lead_period">
            <el-input-number v-model="product.pi_lead_period" :min="0" placeholder="天数" />
          </el-form-item>

          <el-form-item label="厂家供货周期(天)" prop="manufacture_lead_period">
            <el-input-number v-model="product.manufacture_lead_period" :min="0" placeholder="天数" />
          </el-form-item>

          <el-form-item label="备注信息" prop="note">
            <el-input v-model="product.note" type="textarea" placeholder="请输入其他备注信息" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleAddProduct">添加</el-button>
          </el-form-item>
        </el-form>
      </div>

    </el-drawer>
  </el-container>

</template>

<script>
import { Post as CreateOrder } from '@/api/crm/crmorder'
import { Get as GetOrderStatus } from '@/api/crm/crmorderstate'
import { Get as CRMGetProducts } from '@/api/crm/crmproduct'
import { countries, currencys, customer_source } from '../../api/crm/crmcommon'
import qs from 'qs'

export default {
  name: 'Crmcreateorder',
  data() {
    return {
      createloading: false,
      producDrawerVisible: false,
      activeName1: '1',
      activeName2: '2',
      auto_order_no: true,
      temp: {
        name: '',
        manager: this.$store.getters.fullname,
        ending_date: '',
        order_no: '',
        trade_type: '',
        invoice_number: '',
        crmorderstate_id: '',
        currency: 'USD',
        quote: '',
        crmcustomer__name: '',
        crmcustomer__company: '',
        crmcustomer__phone: '',
        crmcustomer__whatsapp: '',
        crmcustomer__country: 'us',
        crmcustomer__source: '独立站',
        crmcustomer__mail: '',
        products: []

      },
      product: {
        cnname: '',
        enname: '',
        sku: '', // SKU编号
        product_type: '主产品', // 产品类型，默认为'main'
        image: '', // 图片URL或路径
        quantity: 1, // 数量，默认为1
        model: '', // 产品型号
        parameters: '', // 技术参数等其他信息
        pi_lead_period: 3, // PI交货周期天，默认为3
        manufacture_lead_period: 3, // 厂家供货周期，默认为3
        note: '' // 其他备注信息
      },
      orderstatesloading: false,
      orderStates: [],
      customer_sources: customer_source,
      countries: countries,
      currencys: currencys,
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '明天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '3天后',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 3)
            picker.$emit('pick', date)
          }
        },
        {
          text: '一周后',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        },
        {
          text: '15天后',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 15)
            picker.$emit('pick', date)
          }
        },
        {
          text: '一个月后',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 30)
            picker.$emit('pick', date)
          }
        }
        ]
      },
      rules: {
        name: [
          { required: true, message: '请输入方便自己查询的订单名称', trigger: 'blur' },
          { min: 3, max: 120, message: '长度在 3 到120个字符', trigger: 'blur' }
        ],
        currency: [
          { required: true, message: '必须选择币种', trigger: 'blur' }
        ],
        crmcustomer__name: [
          { required: true, message: '客户名称', trigger: 'blur' },
          { min: 1, max: 120, message: '长度在 3 到120个字符', trigger: 'blur' }
        ]
      },
      product_rules: {
        cnname: [
          { required: true, message: '产品名称必须填写', trigger: 'blur' },
          { min: 1, max: 120, message: '长度在 3 到120个字符', trigger: 'blur' }
        ]
      },
      width: '',
      timeout: null,
      products: [],
      innerDialogVisible: false
    }
  },
  created() {
    this.handleGetOrderState()
  },
  methods: {
    resetTemp() {
      this.temp = {
        keywords: []
      }
    },
    handleDeleteFromTable(index) {
      this.temp.products.splice(index, 1)
    },
    handleGetProducts(query, cb) {
      CRMGetProducts(null, qs.stringify({
        kw: query,
        pagesize: 10,
        page: 1
      }))
        .then(response => {
          this.products = response.data.data
          if (this.products && this.products.length > 0) {
            this.products.map(function(product) {
              product.value = product.cnname
            })
            cb(this.products)
          }
        }).catch(err => {
          console.log(err)
          this.productlistloading = false
        })
    },
    handleProductSelect(row) {
      // 复制
      Object.keys(this.product).forEach(key => {
        if (row[key] !== undefined) this.product[key] = row[key]
      })
    },
    querySearchProduct(queryString, cb) {
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        this.handleGetProducts(queryString, cb)
      }, 3000 * Math.random())
    },
    handleAddProduct() {
      this.$refs['product'].validate((valid) => {
        if (valid) {
          this.temp.products.push({ ...this.product })
          this.$message({
            message: '添加成功',
            type: 'success'
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleGetOrderState() {
      this.orderstatesloading = true
      GetOrderStatus().then(response => {
        this.orderStates = response.data.data.reverse()
        if (this.orderStates !== undefined && this.orderStates) {
          this.temp.crmorderstate_id = this.orderStates[0].id
        }
        this.orderstatesloading = false
      }).catch(err => {
        console.log(err)
        this.orderstatesloading = false
      })
    },
    handleCreateOrder() {
      this.createloading = true
      CreateOrder(this.temp
      ).then(response => {
        this.notify('添加成功')
        this.createloading = false
      }).catch(err => {
        console.log(err)
        this.createloading = false
      })
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.top >>> .el-select .el-input {
  width: 350px;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin-top: 60px;
  /*margin: 168px auto !important;*/
}
.el-collapse-item__header {
  font-size: 18px;
}
.mt-dialog >>> .el-dialog__body {
  padding-bottom: 100px;
}

/* 添加底部填充防止内容被footer遮挡 */
.el-main {
  padding-bottom: 100px !important;
}

/* 增加基本信息表单的底部间距 */
.form-row {
  margin-bottom: 30px;
  padding-bottom: 20px;
}

/* 优化折叠面板样式 */
.el-collapse {
  margin-bottom: 30px;
}

.el-collapse-item {
  margin-bottom: 20px;
}

/* 表格容器样式优化 */
.el-table {
  margin-bottom: 15px;
}

/* 提示信息间距优化 */
.el-alert {
  margin-top: 10px;
}

/* 抽屉组件内容区域样式 */
.el-drawer__body {
  overflow-y: auto;
  padding-bottom: 60px;
}

.el-drawer__container {
  overflow: visible;
}
</style>
